// src/hooks/useFormValidation.ts
import { useForm } from "react-hook-form";
import * as yup from "yup";
import { yupResolver } from "@hookform/resolvers/yup";

// 定义验证规则
const validationSchema = yup
  .object({
    name: yup.string().required("姓名不能为空123").matches(/^[^\d]*$/, "名字中不能包含数字"),
    position: yup.string().required("请选择职位"),
    resume: yup.string().required("简历不能为空"),
    profileImage: yup
      .mixed<File>()
      .nullable()
      .required("头像不能为空")
      .test("fileType", "仅支持JPEG、PNG、GIF格式的图片", (value) => {
        return (
          value instanceof File &&
          ["image/jpeg", "image/png", "image/gif"].includes(value.type)
        );
      }),
  })
  .required();

// 让 FormData 类型由 yup 推断
type FormData = yup.InferType<typeof validationSchema>;

// 使用 react-hook-form 的 useForm 来处理表单和验证
export const useFormValidationHook = () => {
  const {
    register,
    handleSubmit,
    control,
    setValue,
    watch,
    formState: { errors, isValid },
    reset,
  } = useForm<FormData>({
    mode: "onBlur",
    resolver: yupResolver(validationSchema),
    defaultValues: {
      name: "",
      position: "",
      resume: "",
      profileImage: undefined, // 初始值为 null
    },
  });

  return {
    register,
    handleSubmit,
    control,
    setValue,
    watch,
    errors,
    isValid,
    reset,
  };
};
